<template>
  <div class="plugin-config-upload-page">
    <el-card class="aui-card--fill" shadow="never">
      <el-form inline ref="dataForm">
        <el-form-item>
          <el-input type="text" placeholder="SN8" v-model="sn8">
            <template slot="prepend">型号</template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-radio-group v-model="isPROD">
            <el-radio-button :label="0">测试</el-radio-button>
            <el-radio-button :label="1">正式</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="loadJSON"
            v-loading="loading"
            :disabled="!sn8 || sn8.length <= 0"
          >
            <span><i class="el-icon-download"></i></span>
            <span>加载JSON</span></el-button
          >
        </el-form-item>
      </el-form>
      <div class="content" v-loading="loading || uploading">
        <div class="editor-head">
          <h3>JSON内容：</h3>
          <el-button type="primary" @click="clickOnUpdate">更新配置</el-button>
        </div>
        <MonacoEditor
          class="code-editor-container"
          ref="codeEditor"
          v-model="jsonContent"
          language="json"
          line-numbers="false"
          theme="vs-dark"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
import MonacoEditor from 'vue-monaco'
import Cookies from 'js-cookie'
export default {
  name: 'plugin-config-upload',
  components: { MonacoEditor },
  data () {
    return {
      baseURL: 'http://101.37.158.109:8808/mike-config/combine',
      sn8: '',
      isPROD: 0,
      jsonContent: '{}',
      loading: false,
      uploading: false
    }
  },
  mounted () {},
  methods: {
    clickOnUpdate () {
      console.log(this.jsonContent)
      // http://101.37.158.109:8089/cloud-platform/plugin/plugin_config_upload/config_upload?token=5ffcf3c950c284893f4c7eda9d35f1de

      this.uploading = true
      let token = Cookies.get('token')

      let blob = new Blob([this.jsonContent], {
        type: 'text/json;charset=utf-8'
      })
      let file = new File(
        [blob],
        `device_configs${this.isPROD ? '' : '_sit'}.json`,
        { type: 'text/json;charset=utf-8', lastModified: Date.now() }
      )

      console.log(file)

      let formData = new FormData()
      formData.append(
        'uri',
        `/${this.sn8}/device_configs${this.isPROD ? '' : '_sit'}.json`
      )
      formData.append(
        'file',
        file,
        `device_configs${this.isPROD ? '' : '_sit'}.json`
      )
      axios({
        url: `http://101.37.158.109:8089/cloud-platform/plugin/plugin_config_upload/config_upload?token=${token}`,
        method: 'post',
        onUploadProgress: progressEvent => {
          console.log(progressEvent)
          console.log(
            Math.round((progressEvent.loaded / progressEvent.total) * 100) + '%'
          )
        },
        data: formData
      })
        .then(res => {
          if (res && res.data && res.data.code === 0) {
            this.$message.success('更新成功')

            this.loadJSON()
            return
          }
          this.$message.error(res.data.msg)
        })
        .finally(() => {
          this.uploading = false
        })
    },
    loadJSON () {
      this.loading = true
      axios({
        url: `${this.baseURL}/${this.sn8}/device_configs${
          this.isPROD ? '' : '_sit'
        }.json?_t=${new Date().getTime()}`,
        method: 'get',
        crossDomain: true,
        headers: {
          Accept: '*/*',
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
        .then(res => {
          if (!res || res.status !== 200) {
            return
          }
          this.jsonContent = JSON.stringify(res.data)
          let editor = this.$refs.codeEditor.getEditor()
          editor.trigger('', 'editor.action.formatDocument')
        })
        // eslint-disable-next-line handle-callback-err
        .catch(err => {
          // probably doesn't exist

          this.$message.warning('该型号尚未有配置JSON')
          // this.$message.error(JSON.stringify(err))
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style scoped>
.code-editor-container {
  min-height: 70vh;
}
.content {
  border-top: 1px solid #eeeeee;
  padding-top: 10px;
}
.editor-head {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
</style>
